package com.nsash.chat.async;

import java.io.IOException;

import android.os.AsyncTask;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;

import com.nsash.dto.ChatMessages;
import com.nsash.dto.Message;
import com.nsash.dto.MessageData;
import com.rabbit.chat.core.IRabbitChat;
import com.rabbit.chat.core.RabbitChat;

public class ChatTask extends AsyncTask<String, Message, Void> {
	/**
	 * 
	 */
	private IRabbitChat client;
	private ListAdapter adapter;
	private ChatMessages messages; 
	
	private int messageCount = 0;
	private String receiver;
	public ChatTask(ListAdapter mAdapter, ChatMessages messages, String room){
		this.adapter = mAdapter;
		this.messages = messages;
		receiver = "Silvia";
		client = new RabbitChat(receiver, room){
			@Override
			public void OnMessageReceive(String sender, String message) {
				publishProgress(new Message(Integer.toString(messageCount++), new MessageData(sender, message)));
			}
			
			public void OnError(Exception e) {};
			
		};
	}
	
    protected Void doInBackground(String... urls) {
    	try {
			client.Initialize();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        while(!this.isCancelled()){
        	try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        return null;
    }
    
    @Override
    protected void onProgressUpdate(Message... values) {
    	//messages.addItem(values[0]);
    	((ArrayAdapter<Message>)this.adapter).add(values[0]);
    	((ArrayAdapter<Message>)adapter).notifyDataSetChanged();
    }

    @Override
    protected void onCancelled() {
    	// TODO Auto-generated method stub
    	try {
			client.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	super.onCancelled();
    }
    
    @Override
    protected void onCancelled(Void param) {
    	// TODO Auto-generated method stub
    	try {
			client.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	super.onCancelled();
    }
    
    public void sendMessage(String message) throws Exception{
    	client.SendMessage(message);
    }
}